<?php

namespace App\Http\Controllers\Admin;

use App\CodeResponse;
use App\Http\Controllers\Controller;
use App\Models\Expert;
use App\Services\ExpertService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ExpertController extends AdminController
{
    //保存
    public function save(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'integer|digits_between:1,20|min:1',
            'name' => 'required|string',
            'pic' => 'required|string',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }


        $putData = $request->except(['_method', '_token']);
        $id = $request->input('id');
        $flight = Expert::updateOrCreate(
            ['id' => $id],
            $putData
        );
        return $this->success($flight->id);
    }

    //列表
    public function  list(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'string',
            'page' => 'integer',
            'limit' => 'integer',
            'sort' => 'string',
            'order' => 'string',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $name = $request->input('name');
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 10);
        $sort = $request->input('sort', 'created_at');
        $order = $request->input('order', 'asc');

        $list = ExpertService::getInstance()->list($page, $limit, $sort, $order, $name);
        return $this->success($list);
    }

    public function info(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $id = $request->input('id');
        $info = ExpertService::getInstance()->info($id);
        return $this->success($info);
    }

    //删除
    public function delete(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $expert = Expert::find($request->id);
        $expert->delete();
        return $this->success();
    }

    // 上传结果
    public function upfile(Request $request)
    {
        $url = config('filesystems.disks.expert.url');
        $default = config('filesystems.disks.expert.default');
        $file = ExpertService::getInstance()->upfile($request, $url, $default, 'expert');
        return $this->success([
                'file' => $file,
            ]
        );
    }
}
